package com.isnmp.common.snmp.trap;

import java.util.LinkedList;

import org.snmp4j.Snmp;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.transport.DefaultUdpTransportMapping;

import com.isnmp.common.base.MyException;
import com.isnmp.common.base.MyLog;
import com.isnmp.common.snmp.SNMPSysConfig;

public class TrapReceiverServer {
    static final LinkedList<TrapMessageInfo> eventQueue = new LinkedList();

    public static void startTrapServer() throws MyException {
        try {
            System.out.println("Starting SNMP Trap Receiver......");
            UdpAddress localUdpAddress = new UdpAddress(SNMPSysConfig.SnmpTrapPort);
            DefaultUdpTransportMapping localDefaultUdpTransportMapping = new DefaultUdpTransportMapping(localUdpAddress);
            Snmp localSnmp = new Snmp(localDefaultUdpTransportMapping);
            localSnmp.addCommandResponder(new TrapReceiverImpl());
            localSnmp.listen();
            System.out.println("Started SNMP TRAP Receiver OK!");
        } catch (Exception localException) {
            throw new MyException("Staring SNMP TRAP Erro:" + localException.getMessage());
        }
    }

    public static TrapMessageInfo getTrap() {
        synchronized (eventQueue) {
            while (eventQueue.isEmpty())
                try {
                    eventQueue.wait();
                } catch (Exception localException) {
                    MyLog.err("Get Trap message from queue erro:" + localException.getMessage());
                    MyLog.debug(localException);
                }
            return (TrapMessageInfo) eventQueue.removeFirst();
        }
    }
}